<?php
// students_api.php
include 'config.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

// 添加登录验证端点
if(isset($_GET['action']) && $_GET['action'] == 'login') {
    verifyLogin($db);
    exit;
}

switch($method) {
    case 'GET':
        if(isset($_GET['class'])) {
            $class = $_GET['class'];
            getStudents($db, $class);
        } else {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "缺少班级参数"
            ]);
        }
        break;
        
    case 'POST':
        addStudent($db);
        break;
        
    case 'PUT':
        updateStudent($db);
        break;
        
    case 'DELETE':
        deleteStudent($db);
        break;
        
    default:
        http_response_code(405);
        echo json_encode([
            "success" => false,
            "error" => "不支持的请求方法"
        ]);
        break;
}

// 登录验证函数
function verifyLogin($db) {
    // 设置更长的执行时间以防网络延迟
    set_time_limit(30);
    
    $input = json_decode(file_get_contents("php://input"), true);
    
    if(!isset($input['class']) || !isset($input['studentId']) || !isset($input['studentName'])) {
        http_response_code(400);
        echo json_encode([
            "success" => false,
            "error" => "缺少必要参数：班级、学号或姓名"
        ]);
        return;
    }
    
    $class = $input['class'];
    $studentId = $input['studentId'];
    $studentName = $input['studentName'];
    
    // 参数验证
    if(empty($class) || empty($studentId) || empty($studentName)) {
        http_response_code(400);
        echo json_encode([
            "success" => false,
            "error" => "班级、学号和姓名不能为空"
        ]);
        return;
    }
    
    // 验证班级参数
    if($class != '1' && $class != '2') {
        http_response_code(400);
        echo json_encode([
            "success" => false,
            "error" => "班级参数无效"
        ]);
        return;
    }
    
    try {
        $table_name = $class == 1 ? "数字媒体技术1班" : "数字媒体技术2班";
        
        // 准备查询语句
        $query = "SELECT 学号, 姓名 FROM `$table_name` WHERE 学号 = :studentId AND 姓名 = :studentName";
        $stmt = $db->prepare($query);
        
        // 绑定参数
        $stmt->bindParam(":studentId", $studentId);
        $stmt->bindParam(":studentName", $studentName);
        
        // 执行查询
        $stmt->execute();
        
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($student) {
            // 登录成功
            echo json_encode([
                "success" => true,
                "message" => "登录成功",
                "student" => $student
            ]);
            
            // 记录登录日志（可选）
            error_log("学生登录成功: 班级{$class} - {$studentName}({$studentId}) - " . date('Y-m-d H:i:s'));
            
        } else {
            // 登录失败
            http_response_code(401);
            echo json_encode([
                "success" => false,
                "error" => "学号或姓名不正确，请检查后重试"
            ]);
            
            // 记录失败日志（可选）
            error_log("学生登录失败: 班级{$class} - {$studentName}({$studentId}) - " . date('Y-m-d H:i:s'));
        }
        
    } catch(PDOException $exception) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "系统错误，请稍后重试: " . $exception->getMessage()
        ]);
        
        // 记录错误日志
        error_log("登录验证数据库错误: " . $exception->getMessage());
    }
}

// 获取学生列表
function getStudents($db, $class) {
    try {
        // 验证班级参数
        if($class != '1' && $class != '2') {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级参数无效"
            ]);
            return;
        }
        
        $table_name = $class == 1 ? "数字媒体技术1班" : "数字媒体技术2班";
        $homepage_field = $class == 1 ? "作业主页" : "主页";
        
        $query = "SELECT 学号 as id, 姓名 as name, $homepage_field as homepage FROM `$table_name` ORDER BY 学号";
        $stmt = $db->prepare($query);
        $stmt->execute();
        
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            "success" => true,
            "data" => $students,
            "count" => count($students)
        ]);
        
    } catch(PDOException $exception) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "获取学生数据失败: " . $exception->getMessage()
        ]);
    }
}

// 添加学生
function addStudent($db) {
    try {
        $input = json_decode(file_get_contents("php://input"), true);
        
        if(!isset($input['class']) || !isset($input['id']) || !isset($input['name'])) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "缺少必要参数"
            ]);
            return;
        }
        
        $class = $input['class'];
        $studentId = $input['id'];
        $studentName = $input['name'];
        $homepage = isset($input['homepage']) ? $input['homepage'] : '';
        
        // 参数验证
        if(empty($class) || empty($studentId) || empty($studentName)) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级、学号和姓名不能为空"
            ]);
            return;
        }
        
        // 验证班级参数
        if($class != '1' && $class != '2') {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级参数无效"
            ]);
            return;
        }
        
        $table_name = $class == 1 ? "数字媒体技术1班" : "数字媒体技术2班";
        $homepage_field = $class == 1 ? "作业主页" : "主页";
        
        // 检查学号是否已存在
        $checkQuery = "SELECT 学号 FROM `$table_name` WHERE 学号 = :studentId";
        $checkStmt = $db->prepare($checkQuery);
        $checkStmt->bindParam(":studentId", $studentId);
        $checkStmt->execute();
        
        if($checkStmt->fetch()) {
            http_response_code(409);
            echo json_encode([
                "success" => false,
                "error" => "学号已存在，无法添加重复学号"
            ]);
            return;
        }
        
        $query = "INSERT INTO `$table_name` (学号, 姓名, $homepage_field) VALUES (:id, :name, :homepage)";
        $stmt = $db->prepare($query);
        
        $stmt->bindParam(":id", $studentId);
        $stmt->bindParam(":name", $studentName);
        $stmt->bindParam(":homepage", $homepage);
        
        if($stmt->execute()) {
            echo json_encode([
                "success" => true, 
                "message" => "学生添加成功"
            ]);
            
            // 记录操作日志
            error_log("添加学生成功: 班级{$class} - {$studentName}({$studentId}) - " . date('Y-m-d H:i:s'));
            
        } else {
            http_response_code(500);
            echo json_encode([
                "success" => false,
                "error" => "添加学生失败"
            ]);
        }
    } catch(PDOException $exception) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "添加学生失败: " . $exception->getMessage()
        ]);
        
        // 记录错误日志
        error_log("添加学生数据库错误: " . $exception->getMessage());
    }
}

// 更新学生信息
function updateStudent($db) {
    try {
        $input = json_decode(file_get_contents("php://input"), true);
        
        if(!isset($input['class']) || !isset($input['id']) || !isset($input['name'])) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "缺少必要参数"
            ]);
            return;
        }
        
        $class = $input['class'];
        $studentId = $input['id'];
        $studentName = $input['name'];
        $homepage = isset($input['homepage']) ? $input['homepage'] : '';
        
        // 参数验证
        if(empty($class) || empty($studentId) || empty($studentName)) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级、学号和姓名不能为空"
            ]);
            return;
        }
        
        // 验证班级参数
        if($class != '1' && $class != '2') {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级参数无效"
            ]);
            return;
        }
        
        $table_name = $class == 1 ? "数字媒体技术1班" : "数字媒体技术2班";
        $homepage_field = $class == 1 ? "作业主页" : "主页";
        
        // 检查学生是否存在
        $checkQuery = "SELECT 学号 FROM `$table_name` WHERE 学号 = :studentId";
        $checkStmt = $db->prepare($checkQuery);
        $checkStmt->bindParam(":studentId", $studentId);
        $checkStmt->execute();
        
        if(!$checkStmt->fetch()) {
            http_response_code(404);
            echo json_encode([
                "success" => false,
                "error" => "学生不存在"
            ]);
            return;
        }
        
        $query = "UPDATE `$table_name` SET 姓名 = :name, $homepage_field = :homepage WHERE 学号 = :id";
        $stmt = $db->prepare($query);
        
        $stmt->bindParam(":id", $studentId);
        $stmt->bindParam(":name", $studentName);
        $stmt->bindParam(":homepage", $homepage);
        
        if($stmt->execute()) {
            if($stmt->rowCount() > 0) {
                echo json_encode([
                    "success" => true, 
                    "message" => "学生信息更新成功"
                ]);
                
                // 记录操作日志
                error_log("更新学生信息成功: 班级{$class} - {$studentName}({$studentId}) - " . date('Y-m-d H:i:s'));
                
            } else {
                http_response_code(404);
                echo json_encode([
                    "success" => false,
                    "error" => "学生不存在或数据未更改"
                ]);
            }
        } else {
            http_response_code(500);
            echo json_encode([
                "success" => false,
                "error" => "更新学生信息失败"
            ]);
        }
    } catch(PDOException $exception) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "更新学生信息失败: " . $exception->getMessage()
        ]);
        
        // 记录错误日志
        error_log("更新学生信息数据库错误: " . $exception->getMessage());
    }
}

// 删除学生
function deleteStudent($db) {
    try {
        $input = json_decode(file_get_contents("php://input"), true);
        
        if(!isset($input['class']) || !isset($input['id'])) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "缺少必要参数"
            ]);
            return;
        }
        
        $class = $input['class'];
        $studentId = $input['id'];
        
        // 参数验证
        if(empty($class) || empty($studentId)) {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级和学号不能为空"
            ]);
            return;
        }
        
        // 验证班级参数
        if($class != '1' && $class != '2') {
            http_response_code(400);
            echo json_encode([
                "success" => false,
                "error" => "班级参数无效"
            ]);
            return;
        }
        
        $table_name = $class == 1 ? "数字媒体技术1班" : "数字媒体技术2班";
        
        // 检查学生是否存在
        $checkQuery = "SELECT 学号, 姓名 FROM `$table_name` WHERE 学号 = :studentId";
        $checkStmt = $db->prepare($checkQuery);
        $checkStmt->bindParam(":studentId", $studentId);
        $checkStmt->execute();
        
        $student = $checkStmt->fetch(PDO::FETCH_ASSOC);
        if(!$student) {
            http_response_code(404);
            echo json_encode([
                "success" => false,
                "error" => "学生不存在"
            ]);
            return;
        }
        
        $query = "DELETE FROM `$table_name` WHERE 学号 = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(":id", $studentId);
        
        if($stmt->execute()) {
            if($stmt->rowCount() > 0) {
                echo json_encode([
                    "success" => true, 
                    "message" => "学生删除成功"
                ]);
                
                // 记录操作日志
                error_log("删除学生成功: 班级{$class} - {$student['姓名']}({$studentId}) - " . date('Y-m-d H:i:s'));
                
            } else {
                http_response_code(404);
                echo json_encode([
                    "success" => false,
                    "error" => "学生不存在"
                ]);
            }
        } else {
            http_response_code(500);
            echo json_encode([
                "success" => false,
                "error" => "删除学生失败"
            ]);
        }
    } catch(PDOException $exception) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "删除学生失败: " . $exception->getMessage()
        ]);
        
        // 记录错误日志
        error_log("删除学生数据库错误: " . $exception->getMessage());
    }
}

// 健康检查端点（可选）
if(isset($_GET['action']) && $_GET['action'] == 'health') {
    try {
        $db->query("SELECT 1");
        echo json_encode([
            "success" => true,
            "message" => "数据库连接正常",
            "timestamp" => date('Y-m-d H:i:s')
        ]);
    } catch(PDOException $e) {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "error" => "数据库连接异常: " . $e->getMessage()
        ]);
    }
    exit;
}
?>